package net.mihome.app.ui;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.PauseOnScrollListener;

import net.mihome.app.AppContext;
import net.mihome.app.R;
import net.mihome.app.adapter.BuyCarAdapter;
import net.mihome.app.bean.BuyCar;
import net.mihome.app.bean.URLs;
import net.mihome.app.bean.User;
import net.mihome.app.bean.net.ResponsePojo;
import net.mihome.app.common.UIHelper;
import net.mihome.app.ui.view.MyViewLinster;
import net.mihome.app.utils.MiAsyncHttpResponseHandler;
import net.mihome.app.utils.RequestParamsFactory;

import org.apache.http.Header;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import me.maxwin.view.XListView;

/**
 * Created by zhao on 2015/2/9.
 */
public class BuyCarActivity  extends  BaseActivity {
    private XListView buyCarListview;
    private List<BuyCar> buyCarList=new ArrayList<>();
    private User adminUser;
    private TextView buyCarNum;
    private BuyCarAdapter buyCarAdapter;
    protected static final String STATE_PAUSE_ON_SCROLL = "STATE_PAUSE_ON_SCROLL";
    protected static final String STATE_PAUSE_ON_FLING = "STATE_PAUSE_ON_FLING";
    protected boolean pauseOnScroll = false;
    protected boolean pauseOnFling = true;
    private ImageLoader imageLoader;
    private int begin=0;
    private int num=10;
    public final static int CALL_WUYE_CODE=100;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.buy_car_main);
        buyCarNum= (TextView) findViewById(R.id.buy_car_sum);
        buyCarListview= (XListView) findViewById(R.id.mifuwu_buycar_listview);
        imageLoader= ImageLoader.getInstance();
        buyCarListview.setOnScrollListener(new PauseOnScrollListener(imageLoader, pauseOnScroll, pauseOnFling));
        buyCarAdapter = new BuyCarAdapter(this,R.layout.goods_listitem, buyCarList,imageLoader,new MyViewLinster() {
            @Override
            public void onLoadComplete() {
                refreshData(AddType.REPLACE);
            }

            @Override
            public void onBeforeLoad() {

            }
        });
        buyCarListview.setAdapter(buyCarAdapter);
        refreshData(AddType.ADD_TO_FIRST);
        initAdminUserInfo();
    }

    /**
     * 加载购物车数据
     * */
    public void refreshData(final AddType addType){
        RequestParams requestParams= RequestParamsFactory.newInstance(AppContext.getInstance());
        requestParams.put("begin",begin);
        requestParams.put("num",num);
        AppContext.ASYNC_HTTP_CLIENT.get(this, URLs.MIHOME_GET_GOODS_BUYCAR_LIST,requestParams,new MiAsyncHttpResponseHandler<List<Map>>() {
            @Override
            public void onSuccess(int arg0, Header[] arg1, ResponsePojo<List<Map>> responsePojo) {
                List<BuyCar> buyCarListTemp=BuyCar.parseList(responsePojo.getData());
                if(buyCarListTemp!=null){
                    if(addType==AddType.ADD_TO_FIRST){
                        buyCarList.addAll(0, buyCarListTemp);
                    }else if(addType==AddType.ADD_TO_LAST){
                        buyCarList.addAll(buyCarListTemp);
                    }else{
                        buyCarList.clear();
                        buyCarList.addAll(buyCarListTemp);
                    }
                    refresh();
                    buyCarAdapter.notifyDataSetChanged();
                    //计算总金额
                    BigDecimal moneySum=new BigDecimal(0);
                    Iterator<BuyCar> iterator=buyCarList.iterator();
                    while(iterator.hasNext()){
                        BuyCar buyCar=iterator.next();
                        BigDecimal price=new BigDecimal(buyCar.getGoods().getPrice());
                        BigDecimal buyNum=new BigDecimal(buyCar.getNum());
                        BigDecimal all=price.multiply(buyNum);
                        moneySum=moneySum.add(all);
                    }
                    double   f1   =   moneySum.setScale(2,   BigDecimal.ROUND_HALF_UP).doubleValue();
                    ((TextView)findViewById(R.id.all_price)).setText(f1+"");
                }
            }
            @Override
            public void onFailure(int arg0, Header[] arg1, Throwable arg3) {
                Toast.makeText(BuyCarActivity.this,"获取购物车信息发生错误"+arg3.getMessage(),Toast.LENGTH_SHORT).show();
            }
        });
    }
    /**
     * 下一页
     * */
    public void nextPage(){
        begin=(begin+1)*num;
        refreshData(AddType.ADD_TO_LAST);
    }
    /**
     * 上一页
     * */
    public void prePage(){
        begin=begin-num;
        if(begin<0){
            begin=0;
        }
        num=10;
        refreshData(AddType.ADD_TO_FIRST);
    }
    /**
     * 刷新当前页
     * */
    public void currentPage(){
        refreshData(AddType.REPLACE);
    }
    /**
     * 第一页
     * */
    public void firstPage(){
        begin=0;
        refreshData(AddType.REPLACE);
    }
    /**
     * 跳到指定页
     * */
    public void redirtoBegin(int begin){
        this.begin=begin;
        refreshData(AddType.REPLACE);
    }
    public enum AddType{
        ADD_TO_LAST,ADD_TO_FIRST,REPLACE
    }
    /**
     * 初始化物业公司管理员信息
     * */
    public void initAdminUserInfo(){
        RequestParams requestParams= RequestParamsFactory.newInstance(AppContext.getInstance());
        AppContext.ASYNC_HTTP_CLIENT.get(this, URLs.MIHOME_USER_GET_COMMUNITY_ADMIN,requestParams,new MiAsyncHttpResponseHandler<Map>() {
            @Override
            public void onSuccess(int arg0, Header[] arg1, ResponsePojo<Map> responsePojo) {
                adminUser=User.parse(responsePojo.getData());
            }
            @Override
            public void onFailure(int arg0, Header[] arg1, Throwable arg3) {
                Toast.makeText(BuyCarActivity.this, "请求小区超市信息失败" + arg3.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }
    /**
     * 呼叫送货电话
     * */
    public void callWuye(View view){
        if(adminUser==null||adminUser.getMobile()==null||"".equals(adminUser.getMobile().trim())){
            Toast.makeText(this,"物业管理员信息无效,请于物业公司联系",Toast.LENGTH_SHORT).show();
            return;
        }
        String mobile=adminUser.getMobile();
        if(adminUser.getCommunity().getShopMobile()!=null&&!"".equals(adminUser.getCommunity().getShopMobile())){
            mobile=adminUser.getCommunity().getShopMobile();
        }
        String[] items=mobile.split(",|，|、");
        UIHelper.simpleDialog(this,items,CALL_WUYE_CODE);
    }
    /**
     * 发送购物车商品给送货人
     * */
    public void createOrder(View view){

    }
    /**
     * 刷新购物车的数量
     * */
    public void refresh(){
        RequestParams requestParams= RequestParamsFactory.newInstance(AppContext.getInstance());
        AppContext.ASYNC_HTTP_CLIENT.get(this, URLs.MIHOME_GET_GOODS_BUYCAR_COUNT,requestParams,new MiAsyncHttpResponseHandler<String>() {
            @Override
            public void onSuccess(int arg0, Header[] arg1, ResponsePojo<String> responsePojo) {
                String numStrig=responsePojo.getData();
                Long num=Long.parseLong(numStrig);
                if(num>0){
                    buyCarNum.setVisibility(View.VISIBLE);
                    buyCarNum.setText(num.intValue()+"");
                }else{
                    buyCarNum.setVisibility(View.GONE);
                }
            }

            @Override
            public void onFailure(int arg0, Header[] arg1, Throwable arg3) {

            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode==CALL_WUYE_CODE){
            AlertDialog.Builder builder=new AlertDialog.Builder(this);
            builder.setTitle("提示:");
            builder.setMessage("是否通过短信下单?");
            builder.setNegativeButton("取消",new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    dialogInterface.dismiss();
                }
            });
            builder.setPositiveButton("下单",new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    dialogInterface.dismiss();
                    makeOrder();
                }
            });
            builder.show();
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
    /**
     * 下单
     * */
    public void makeOrder(){
        AlertDialog.Builder builder= new AlertDialog.Builder(this);
        builder.setTitle("下单中");
        builder.setMessage("正在下单...");
        final AlertDialog alertDialog=builder.show();
        RequestParams requestParams=RequestParamsFactory.newInstance(AppContext.getInstance());
        AppContext.ASYNC_HTTP_CLIENT.get(this,URLs.MIHOME_GET_GOODS_MAKE_ORDER,requestParams,new MiAsyncHttpResponseHandler<Map>() {
            @Override
            public void onSuccess(int arg0, Header[] arg1, ResponsePojo<Map> responsePojo) {
                alertDialog.setMessage("下单成功");
                String message= (String) responsePojo.getData().get("msg");
                String mobile=adminUser.getMobile().trim();
                if(adminUser.getCommunity()!=null&&adminUser.getCommunity().getShopMobile()!=null){
                    mobile=adminUser.getCommunity().getShopMobile().trim();
                }
                Uri uri= Uri.parse("smsto://"+mobile);
                Intent ii=new Intent(Intent.ACTION_SENDTO,uri);//绿色文字就是启动发送短信窗口
                ii.putExtra("sms_body", message);
                startActivity(ii);
                alertDialog.dismiss();
            }

            @Override
            public void onFailure(int arg0, Header[] arg1, Throwable arg3) {
                alertDialog.dismiss();
                Toast.makeText(BuyCarActivity.this,"下单失败,请联系管理员",Toast.LENGTH_SHORT).show();
            }
        });
    }
}